home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Mac-Source 1994 July
/
Mac-Source_July_1994.iso
/
Other Langs
/
python
/
emacs-info
/
python-lib.info-1
< prev
next >
Encoding:
Amiga
Atari
Commodore
DOS
FM Towns/JPY
Macintosh
Macintosh JP
Macintosh to JP
NeXTSTEP
RISC OS/Acorn
Shift JIS
UTF-8
Wrap
GNU Info File
|
1994-04-01
|
50.2 KB
|
1,396 lines
|
[
TEXT/R*ch
]
This is Info file python-lib.info, produced by Makeinfo-1.55 from the
input file lib.texi.
This file describes the built-in types, exceptions and functions and the
standard modules that come with the Python system. It assumes basic
knowledge about the Python language. For an informal introduction to
the language, see the Python Tutorial. The Python Reference Manual
gives a more formal definition of the language. (These manuals are not
yet available in INFO or Texinfo format.)
Copyright (C) 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
File: python-lib.info, Node: Top, Next: Introduction, Prev: (dir), Up: (dir)
The Python library
******************
This file describes the built-in types, exceptions and functions and the
standard modules that come with the Python system. It assumes basic
knowledge about the Python language. For an informal introduction to
the language, see the `Python Tutorial'. The `Python Reference Manual'
gives a more formal definition of the language. (These manuals are not
yet available in INFO or Texinfo format.)
This version corresponds to Python version 1.0.0.
* Menu:
* Introduction::
* Built-in Objects::
* Built-in Modules::
* Standard Modules::
* UNIX ONLY::
* MULTIMEDIA EXTENSIONS::
* CRYPTOGRAPHIC EXTENSIONS::
* STDWIN ONLY::
* SGI IRIX ONLY::
* SUNOS ONLY::
* Function Index::
* Variable Index::
* Module Index::
* Concept Index::
File: python-lib.info, Node: Introduction, Next: Built-in Objects, Prev: Top, Up: Top
Introduction
************
The Python library consists of three parts, with different levels of
integration with the interpreter. Closest to the interpreter are
built-in types, exceptions and functions. Next are built-in modules,
which are written in C and linked statically with the interpreter.
Finally there are standard modules that are implemented entirely in
Python, but are always available. For efficiency, some standard
modules may become built-in modules in future versions of the
interpreter.
File: python-lib.info, Node: Built-in Objects, Next: Built-in Modules, Prev: Introduction, Up: Top
Built-in Types, Exceptions and Functions
****************************************
Names for built-in exceptions and functions are found in a separate
symbol table. This table is searched last, so local and global
user-defined names can override built-in names. Built-in types have no
names but are created easily by constructing an object of the desired
type (e.g., using a literal) and applying the built-in function
`type()' to it. They are described together here for easy reference.(1)
* Menu:
* Types::
* Exceptions::
* Built-in Functions::
---------- Footnotes ----------
(1) Some descriptions sorely lack explanations of the exceptions that
may be raised -- this will be fixed in a future version of this
document.
File: python-lib.info, Node: Types, Next: Exceptions, Prev: Built-in Objects, Up: Built-in Objects
Built-in Types
==============
The following sections describe the standard types that are built into
the interpreter. These are the numeric types, sequence types, and
several others, including types themselves. There is no explicit
Boolean type; use integers instead.
Some operations are supported by several object types; in particular,
all objects can be compared, tested for truth value, and converted to a
string (with the ``...`' notation). The latter conversion is
implicitly used when an object is written by the `print' statement.
* Menu:
* Truth Value Testing::
* Boolean Operations::
* Comparisons::
* Numeric Types::
* Sequence Types::
* Mapping Types::
* Other Built-in Types::
* Special Attributes::
File: python-lib.info, Node: Truth Value Testing, Next: Boolean Operations, Prev: Types, Up: Types
Truth Value Testing
-------------------
Any object can be tested for truth value, for use in an `if' or `while'
condition or as operand of the Boolean operations below. The following
values are false:
* `None'
* zero of any numeric type, e.g., `0', `0L', `0.0'.
* any empty sequence, e.g., `''', `()', `[]'.
* any empty mapping, e.g., `{}'.
*All* other values are true -- so objects of many types are always true.
File: python-lib.info, Node: Boolean Operations, Next: Comparisons, Prev: Truth Value Testing, Up: Types
Boolean Operations
------------------
These are the Boolean operations:
*Operation*
*Result* -- *Notes*
`X or Y'
if X is false, then Y, else X -- (1)
`X and Y'
if X is false, then X, else Y -- (1)
`not X'
if X is false, then `1', else `0'
Notes:
(1)
These only evaluate their second argument if needed for their
outcome.
File: python-lib.info, Node: Comparisons, Next: Numeric Types, Prev: Boolean Operations, Up: Types
Comparisons
-----------
Comparison operations are supported by all objects:
*Operation*
*Meaning* -- *Notes*
`<'
strictly less than
`<='
less than or equal
`>'
strictly greater than
`>='
greater than or equal
`=='
equal
`<>'
not equal -- (1)
`!='
not equal -- (1)
`is'
object identity
`is not'
negated object identity
Notes:
(1)
`<>' and `!=' are alternate spellings for the same operator. (I
couldn't choose between ABC and C! :-)
Objects of different types, except different numeric types, never
compare equal; such objects are ordered consistently but arbitrarily
(so that sorting a heterogeneous array yields a consistent result).
Furthermore, some types (e.g., windows) support only a degenerate
notion of comparison where any two objects of that type are unequal.
Again, such objects are ordered arbitrarily but consistently.
(Implementation note: objects of different types except numbers are
ordered by their type names; objects of the same types that don't
support proper comparison are ordered by their address.)
Two more operations with the same syntactic priority, `in' and `not
in', are supported only by sequence types (below).
File: python-lib.info, Node: Numeric Types, Next: Sequence Types, Prev: Comparisons, Up: Types
Numeric Types
-------------
There are three numeric types: "plain integers", "long integers", and
"floating point numbers". Plain integers (also just called "integers")
are implemented using `long' in C, which gives them at least 32 bits of
precision. Long integers have unlimited precision. Floating point
numbers are implemented using `double' in C. All bets on their
precision are off unless you happen to know the machine you are working
with.
Numbers are created by numeric literals or as the result of built-in
functions and operators. Unadorned integer literals (including hex and
octal numbers) yield plain integers. Integer literals with an `L' or
`l' suffix yield long integers (`L' is preferred because `1l' looks too
much like eleven!). Numeric literals containing a decimal point or an
exponent sign yield floating point numbers.
Python fully supports mixed arithmetic: when a binary arithmetic
operator has operands of different numeric types, the operand with the
"smaller" type is converted to that of the other, where plain integer
is smaller than long integer is smaller than floating point.
Comparisons between numbers of mixed type use the same rule.(1) The
functions `int()', `long()' and `float()' can be used to coerce numbers
to a specific type.
All numeric types support the following operations:
*Operation*
*Result* -- *Notes*
`abs(X)'
absolute value of X
`int(X)'
X converted to integer -- (1)
`long(X)'
X converted to long integer -- (1)
`float(X)'
X converted to floating point
`-X'
X negated
`+X'
X unchanged
`X + Y'
sum of X and Y
`X - Y'
difference of X and Y
`X * Y'
product of X and Y
`X / Y'
quotient of X and Y -- (2)
`X % Y'
remainder of `X / Y'
`divmod(X, Y)'
the pair `(X / Y, X % Y)' -- (3)
`pow(X, Y)'
X to the power Y
Notes:
(1)
Conversion from floating point to (long or plain) integer may
round or truncate as in C; see functions `floor' and `ceil' in
module `math' for well-defined conversions.
(2)
For (plain or long) integer division, the result is an integer; it
always truncates towards zero.
(3)
See the section on built-in functions for an exact definition.
* Menu:
* Bit-string Operations on Integer Types::
---------- Footnotes ----------
(1) As a consequence, the list `[1, 2]' is considered equal to `[1.0,
2.0]', and similar for tuples.
File: python-lib.info, Node: Bit-string Operations on Integer Types, Prev: Numeric Types, Up: Numeric Types
Bit-string Operations on Integer Types.
.......................................
Plain and long integer types support additional operations that make
sense only for bit-strings. Negative numbers are treated as their 2's
complement value:
*Operation*
*Result* -- *Notes*
`~X'
the bits of X inverted
`X ^ Y'
bitwise "exclusive or" of X and Y
`X & Y'
bitwise "and" of X and Y
`X | Y'
bitwise "or" of X and Y
`X << N'
X shifted left by N bits
`X >> N'
X shifted right by N bits
File: python-lib.info, Node: Sequence Types, Next: Mapping Types, Prev: Numeric Types, Up: Types
Sequence Types
--------------
There are three sequence types: strings, lists and tuples. Strings
literals are written in single quotes: `'xyzzy''. Lists are
constructed with square brackets, separating items with commas: `[a, b,
c]'. Tuples are constructed by the comma operator (not within square
brackets), with or without enclosing parentheses, but an empty tuple
must have the enclosing parentheses, e.g., `a, b, c' or `()'. A single
item tuple must have a trailing comma, e.g., `(d,)'.
Sequence types support the following operations (S and T are sequences
of the same type; N, I and J are integers):
*Operation*
*Result* -- *Notes*
`len(S)'
length of S
`min(S)'
smallest item of S
`max(S)'
largest item of S
`X in S'
`1' if an item of S is equal to X, else `0'
`X not in S'
`0' if an item of S is equal to X, else `1'
`S + T'
the concatenation of S and T
`S * N, N * S'
N copies of S concatenated
`S[I]'
I'th item of S, origin 0 -- (1)
`S[I:J]'
slice of S from I to J -- (1), (2)
Notes:
(1)
If I or J is negative, the index is relative to the end of the
string, i.e., `len(S) + I' or `len(S) + J' is substituted. But
note that `-0' is still `0'.
(2)
The slice of S from I to J is defined as the sequence of items
with index K such that `I <= K < J'. If I or J is greater than
`len(S)', use `len(S)'. If I is omitted, use `0'. If J is
omitted, use `len(S)'. If I is greater than or equal to J, the
slice is empty.
* Menu:
* More String Operations::
* Mutable Sequence Types::
File: python-lib.info, Node: More String Operations, Next: Mutable Sequence Types, Prev: Sequence Types, Up: Sequence Types
More String Operations.
.......................
String objects have one unique built-in operation: the `%' operator
(modulo) with a string left argument interprets this string as a C
sprintf format string to be applied to the right argument, and returns
the string resulting from this formatting operation.
Unless the format string requires exactly one argument, the right
argument should be a tuple of the correct size. The following format
characters are understood: %, c, s, i, d, u, o, x, X, e, E, f, g, G.
Width and precision may be a * to specify that an integer argument
specifies the actual width or precision. The flag characters -, +,
blank, # and 0 are understood. The size specifiers h, l or L may be
present but are ignored. The ANSI features `%p' and `%n' are not
supported. Since Python strings have an explicit length, `%s'
conversions don't assume that `'
0'' is the end of the string.
For safety reasons, huge floating point precisions are truncated; `%f'
conversions for huge numbers are replaced by `%g' conversions. All
other errors raise exceptions.
Additional string operations are defined in standard module `string'
and in built-in module `regex'.
File: python-lib.info, Node: Mutable Sequence Types, Prev: More String Operations, Up: Sequence Types
Mutable Sequence Types.
.......................
List objects support additional operations that allow in-place
modification of the object. These operations would be supported by
other mutable sequence types (when added to the language) as well.
Strings and tuples are immutable sequence types and such objects cannot
be modified once created. The following operations are defined on
mutable sequence types (where X is an arbitrary object):
*Operation*
*Result* -- *Notes*
`S[I] = X'
item I of S is replaced by X
`S[I:J] = T'
slice of S from I to J is replaced by T
`del S[I:J]'
same as `S[I:J] = []'
`S.append(X)'
same as `S[len(X):len(X)] = [X]'
`S.count(X)'
return number of I's for which `S[I] == X'
`S.index(X)'
return smallest I such that `S[I] == X' -- (1)
`S.insert(I, X)'
same as `S[I:I] = [X]'
`S.remove(X)'
same as `del S[S.index(X)]' -- (1)
`S.reverse()'
reverses the items of S in place
`S.sort()'
permutes the items of S to satisfy `S[I] <= S[J]', for `I < J' --
(2)
Notes:
(1)
Raises an exception when X is not found in S.
(2)
The `sort()' method takes an optional argument specifying a
comparison function of two arguments (list items) which should
return `-1', `0' or `1' depending on whether the first argument is
considered smaller than, equal to, or larger than the second
argument. Note that this slows the sorting process down
considerably; e.g. to sort an array in reverse order it is much
faster to use calls to `sort()' and `reverse()' than to use
`sort()' with a comparison function that reverses the ordering of
the elements.
File: python-lib.info, Node: Mapping Types, Next: Other Built-in Types, Prev: Sequence Types, Up: Types
Mapping Types
-------------
A "mapping" object maps values of one type (the key type) to arbitrary
objects. Mappings are mutable objects. There is currently only one
mapping type, the "dictionary". A dictionary's keys are almost
arbitrary values. The only types of values not acceptable as keys are
values containing lists or dictionaries or other mutable types that are
compared by value rather than by object identity. Numeric types used
for keys obey the normal rules for numeric comparison: if two numbers
compare equal (e.g. 1 and 1.0) then they can be used interchangeably to
index the same dictionary entry.
Dictionaries are created by placing a comma-separated list of `KEY:
VALUE' pairs within braces, for example: `{'jack': 4098, 'sjoerd:
4127}' or `{4098: 'jack', 4127: 'sjoerd}'.
The following operations are defined on mappings (where A is a mapping,
K is a key and X is an arbitrary object):
*Operation*
*Result* -- *Notes*
`len(A)'
the number of items in A
`A[K]'
the item of A with key K -- (1)
`A[K] = X'
set `A[K]' to X
`del A[K]'
remove `A[K]' from A -- (1)
`A.items()'
a copy of A's list of (key, item) pairs -- (2)
`A.keys()'
a copy of A's list of keys -- (2)
`A.values()'
a copy of A's list of values -- (2)
`A.has_key(K)'
`1' if A has a key K, else `0'
Notes:
(1)
Raises an exception if K is not in the map.
(2)
Keys and values are listed in random order, but at any moment the
ordering of the `keys()', `values()' and `items()' lists is the
consistent with each other.
File: python-lib.info, Node: Other Built-in Types, Next: Special Attributes, Prev: Mapping Types, Up: Types
Other Built-in Types
--------------------
The interpreter supports several other kinds of objects. Most of these
support only one or two operations.
* Menu:
* Modules::
* Classes and Class Instances::
* Functions::
* Methods::
* Type Objects::
* The Null Object::
* File Objects::
* Internal Objects::
File: python-lib.info, Node: Modules, Next: Classes and Class Instances, Prev: Other Built-in Types, Up: Other Built-in Types
Modules.
........
The only special operation on a module is attribute access: `M.NAME',
where M is a module and NAME accesses a name defined in M's symbol
table. Module attributes can be assigned to. (Note that the `import'
statement is not, strictly spoken, an operation on a module object;
`import FOO' does not require a module object named FOO to exist,
rather it requires an (external) *definition* for a module named FOO
somewhere.)
A special member of every module is `__dict__'. This is the dictionary
containing the module's symbol table. Modifying this dictionary will
actually change the module's symbol table, but direct assignment to the
`__dict__' attribute is not possible (i.e., you can write
`M.__dict__['a'] = 1', which defines `M.a' to be `1', but you can't
write `M.__dict__ = {}'.
Modules are written like this: `<module 'sys'>'.
File: python-lib.info, Node: Classes and Class Instances, Next: Functions, Prev: Modules, Up: Other Built-in Types
Classes and Class Instances.
............................
(See the Python Reference Manual for these.)
File: python-lib.info, Node: Functions, Next: Methods, Prev: Classes and Class Instances, Up: Other Built-in Types
Functions.
..........
Function objects are created by function definitions. The only
operation on a function object is to call it: `FUNC(ARGUMENT-LIST)'.
There are really two flavors of function objects: built-in functions
and user-defined functions. Both support the same operation (to call
the function), but the implementation is different, hence the different
object types.
The implementation adds two special read-only attributes: `F.func_code'
is a function's "code object" (see below) and `F.func_globals' is the
dictionary used as the function's global name space (this is the same
as `M.__dict__' where M is the module in which the function F was
defined).
File: python-lib.info, Node: Methods, Next: Type Objects, Prev: Functions, Up: Other Built-in Types
Methods.
........
Methods are functions that are called using the attribute notation.
There are two flavors: built-in methods (such as `append()' on lists)
and class instance methods. Built-in methods are described with the
types that support them.
The implementation adds two special read-only attributes to class
instance methods: `M.im_self' is the object whose method this is, and
`M.im_func' is the function implementing the method. Calling `M(ARG-1,
ARG-2, ..., ARG-N)' is completely equivalent to calling
`M.im_func(M.im_self, ARG-1, ARG-2, ..., ARG-N)'.
(See the Python Reference Manual for more info.)
File: python-lib.info, Node: Type Objects, Next: The Null Object, Prev: Methods, Up: Other Built-in Types
Type Objects.
.............
Type objects represent the various object types. An object's type is
accessed by the built-in function `type()'. There are no special
operations on types.
Types are written like this: `<type 'int'>'.
File: python-lib.info, Node: The Null Object, Next: File Objects, Prev: Type Objects, Up: Other Built-in Types
The Null Object.
................
This object is returned by functions that don't explicitly return a
value. It supports no special operations. There is exactly one null
object, named `None' (a built-in name).
It is written as `None'.
File: python-lib.info, Node: File Objects, Next: Internal Objects, Prev: The Null Object, Up: Other Built-in Types
File Objects.
.............
File objects are implemented using C's `stdio' package and can be
created with the built-in function `open()' described under Built-in
Functions below.
When a file operation fails for an I/O-related reason, the exception
`IOError' is raised. This includes situations where the operation is
not defined for some reason, like `seek()' on a tty device or writing a
file opened for reading.
Files have the following methods:
- Method on file: close ()
Close the file. A closed file cannot be read or written anymore.
- Method on file: flush ()
Flush the internal buffer, like `stdio''s `fflush()'.
- Method on file: isatty ()
Return `1' if the file is connected to a tty(-like) device, else
`0'.
- Method on file: read (SIZE)
Read at most SIZE bytes from the file (less if the read hits EOF
or no more data is immediately available on a pipe, tty or similar
device). If the SIZE argument is omitted, read all data until EOF
is reached. The bytes are returned as a string object. An empty
string is returned when EOF is encountered immediately. (For
certain files, like ttys, it makes sense to continue reading after
an EOF is hit.)
- Method on file: readline ()
Read one entire line from the file. A trailing newline character
is kept in the string (but may be absent when a file ends with an
incomplete line). An empty string is returned when EOF is hit
immediately. Note: unlike `stdio''s `fgets()', the returned
string contains null characters (`'\0'') if they occurred in the
input.
- Method on file: readlines ()
Read until EOF using `readline()' and return a list containing the
lines thus read.
- Method on file: seek (OFFSET, WHENCE)
Set the file's current position, like `stdio''s `fseek()'. The
WHENCE argument is optional and defaults to `0' (absolute file
positioning); other values are `1' (seek relative to the current
position) and `2' (seek relative to the file's end). There is no
return value.
- Method on file: tell ()
Return the file's current position, like `stdio''s `ftell()'.
- Method on file: write (STR)
Write a string to the file. There is no return value.
File: python-lib.info, Node: Internal Objects, Prev: File Objects, Up: Other Built-in Types
Internal Objects.
.................
(See the Python Reference Manual for these.)
File: python-lib.info, Node: Special Attributes, Prev: Other Built-in Types, Up: Types
Special Attributes
------------------
The implementation adds a few special read-only attributes to several
object types, where they are relevant:
* `X.__dict__' is a dictionary of some sort used to store an
object's (writable) attributes;
* `X.__methods__' lists the methods of many built-in object types,
e.g., `[].__methods__' is `['append', 'count', 'index', 'insert',
'remove', 'reverse', 'sort']';
* `X.__members__' lists data attributes;
* `X.__class__' is the class to which a class instance belongs;
* `X.__bases__' is the tuple of base classes of a class object.
File: python-lib.info, Node: Exceptions, Next: Built-in Functions, Prev: Types, Up: Built-in Objects
Built-in Exceptions
===================
Exceptions are string objects. Two distinct string objects with the
same value are different exceptions. This is done to force programmers
to use exception names rather than their string value when specifying
exception handlers. The string value of all built-in exceptions is
their name, but this is not a requirement for user-defined exceptions
or exceptions defined by library modules.
The following exceptions can be generated by the interpreter or
built-in functions. Except where mentioned, they have an `associated
value' indicating the detailed cause of the error. This may be a
string or a tuple containing several items of information (e.g., an
error code and a string explaining the code).
User code can raise built-in exceptions. This can be used to test an
exception handler or to report an error condition `just like' the
situation in which the interpreter raises the same exception; but
beware that there is nothing to prevent user code from raising an
inappropriate error.
- built-in exception: AttributeError
Raised when an attribute reference or assignment fails. (When an
object does not support attributes references or attribute
assignments at all, `TypeError' is raised.)
- built-in exception: EOFError
Raised when one of the built-in functions (`input()' or
`raw_input()') hits an end-of-file condition (EOF) without reading
any data. (N.B.: the `read()' and `readline()' methods of file
objects return an empty string when they hit EOF.) No associated
value.
- built-in exception: IOError
Raised when an I/O operation (such as a `print' statement, the
built-in `open()' function or a method of a file object) fails for
an I/O-related reason, e.g., `file not found', `disk full'.
- built-in exception: ImportError
Raised when an `import' statement fails to find the module
definition or when a `from ... import' fails to find a name that
is to be imported.
- built-in exception: IndexError
Raised when a sequence subscript is out of range. (Slice indices
are silently truncated to fall in the allowed range; if an index
is not a plain integer, `TypeError' is raised.)
- built-in exception: KeyError
Raised when a mapping (dictionary) key is not found in the set of
existing keys.
- built-in exception: KeyboardInterrupt
Raised when the user hits the interrupt key (normally `Control-C'
or DEL). During execution, a check for interrupts is made
regularly. Interrupts typed when a built-in function `input()' or
`raw_input()') is waiting for input also raise this exception. No
associated value.
- built-in exception: MemoryError
Raised when an operation runs out of memory but the situation may
still be rescued (by deleting some objects). The associated value
is a string indicating what kind of (internal) operation ran out
of memory. Note that because of the underlying memory management
architecture (C's `malloc()' function), the interpreter may not
always be able to completely recover from this situation; it
nevertheless raises an exception so that a stack traceback can be
printed, in case a run-away program was the cause.
- built-in exception: NameError
Raised when a local or global name is not found. This applies only
to unqualified names. The associated value is the name that could
not be found.
- built-in exception: OverflowError
Raised when the result of an arithmetic operation is too large to
be represented. This cannot occur for long integers (which would
rather raise `MemoryError' than give up). Because of the lack of
standardization of floating point exception handling in C, most
floating point operations also aren't checked. For plain integers,
all operations that can overflow are checked except left shift,
where typical applications prefer to drop bits than raise an
exception.
- built-in exception: RuntimeError
Raised when an error is detected that doesn't fall in any of the
other categories. The associated value is a string indicating what
precisely went wrong. (This exception is a relic from a previous
version of the interpreter; it is not used any more except by some
extension modules that haven't been converted to define their own
exceptions yet.)
- built-in exception: SyntaxError
Raised when the parser encounters a syntax error. This may occur
in an `import' statement, in an `exec' statement, in a call to the
built-in function `eval()' or `input()', or when reading the
initial script or standard input (also interactively).
- built-in exception: SystemError
Raised when the interpreter finds an internal error, but the
situation does not look so serious to cause it to abandon all hope.
The associated value is a string indicating what went wrong (in
low-level terms).
You should report this to the author or maintainer of your Python
interpreter. Be sure to report the version string of the Python
interpreter (`sys.version'; it is also printed at the start of an
interactive Python session), the exact error message (the
exception's associated value) and if possible the source of the
program that triggered the error.
- built-in exception: SystemExit
This exception is raised by the `sys.exit()' function. When it is
not handled, the Python interpreter exits; no stack traceback is
printed. If the associated value is a plain integer, it specifies
the system exit status (passed to C's `exit()' function); if it is
`None', the exit status is zero; if it has another type (such as a
string), the object's value is printed and the exit status is one.
A call to `sys.exit' is translated into an exception so that
clean-up handlers (`finally' clauses of `try' statements) can be
executed, and so that a debugger can execute a script without
running the risk of losing control. The `posix._exit()' function
can be used if it is absolutely positively necessary to exit
immediately (e.g., after a `fork()' in the child process).
- built-in exception: TypeError
Raised when a built-in operation or function is applied to an
object of inappropriate type. The associated value is a string
giving details about the type mismatch.
- built-in exception: ValueError
Raised when a built-in operation or function receives an argument
that has the right type but an inappropriate value, and the
situation is not described by a more precise exception such as
`IndexError'.
- built-in exception: ZeroDivisionError
Raised when the second argument of a division or modulo operation
is zero. The associated value is a string indicating the type of
the operands and the operation.
File: python-lib.info, Node: Built-in Functions, Prev: Exceptions, Up: Built-in Objects
Built-in Functions
==================
The Python interpreter has a number of functions built into it that are
always available. They are listed here in alphabetical order.
- built-in function: abs (X)
Return the absolute value of a number. The argument may be a plain
or long integer or a floating point number.
- built-in function: apply (FUNCTION, ARGS)
The FUNCTION argument must be a callable object (a user-defined or
built-in function or method, or a class object) and the ARGS
argument must be a tuple. The FUNCTION is called with ARGS as
argument list; the number of arguments is the the length of the
tuple. (This is different from just calling `FUNC(ARGS)', since
in that case there is always exactly one argument.)
- built-in function: chr (I)
Return a string of one character whose ASCII code is the integer
I, e.g., `chr(97)' returns the string `'a''. This is the inverse
of `ord()'. The argument must be in the range [0..255], inclusive.
- built-in function: cmp (X, Y)
Compare the two objects X and Y and return an integer according to
the outcome. The return value is negative if `X < Y', zero if `X
== Y' and strictly positive if `X > Y'.
- built-in function: coerce (X, Y)
Return a tuple consisting of the two numeric arguments converted to
a common type, using the same rules as used by arithmetic
operations.
- built-in function: compile (STRING, FILENAME, KIND)
Compile the STRING into a code object. Code objects can be
executed by a `exec()' statement or evaluated by a call to
`eval()'. The FILENAME argument should give the file from which
the code was read; pass e.g. `'<string>'' if it wasn't read from a
file. The KIND argument specifies what kind of code must be
compiled; it can be `'exec'' if STRING consists of a sequence of
statements, or `'eval'' if it consists of a single expression.
- built-in function: dir ()
Without arguments, return the list of names in the current local
symbol table. With a module, class or class instance object as
argument (or anything else that has a `__dict__' attribute),
returns the list of names in that object's attribute dictionary.
The resulting list is sorted. For example:
>>> import sys
>>> dir()
['sys']
>>> dir(sys)
['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout']
>>>
- built-in function: divmod (A, B)
Take two numbers as arguments and return a pair of integers
consisting of their integer quotient and remainder. With mixed
operand types, the rules for binary arithmetic operators apply.
For plain and long integers, the result is the same as `(A / B, A
% B)'. For floating point numbers the result is the same as
`(math.floor(A / B), A % B)'.
- built-in function: eval (S, GLOBALS, LOCALS)
The arguments are a string and two optional dictionaries. The
string argument is parsed and evaluated as a Python expression
(technically speaking, a condition list) using the dictionaries as
global and local name space. The string must not contain null
bytes or newline characters. The return value is the result of
the expression. If the third argument is omitted it defaults to
the second. If both dictionaries are omitted, the expression is
executed in the environment where `eval' is called. Syntax errors
are reported as exceptions. Example:
>>> x = 1
>>> print eval('x+1')
2
>>>
This function can also be used to execute arbitrary code objects
(e.g. created by `compile()'). In this case pass a code object
instead of a string. The code object must have been compiled
passing `'eval'' to the KIND argument.
Note: dynamic execution of statements is supported by the `exec'
statement.
- built-in function: filter (FUNCTION, LIST)
Construct a list from those elements of LIST for which FUNCTION
returns true. If LIST is a string or a tuple, the result also has
that type; otherwise it is always a list. If FUNCTION is `None',
the identity function is assumed, i.e. all elements of LIST that
are false (zero or empty) are removed.
- built-in function: float (X)
Convert a number to floating point. The argument may be a plain or
long integer or a floating point number.
- built-in function: getattr (OBJECT, NAME)
The arguments are an object and a string. The string must be the
name of one of the object's attributes. The result is the value
of that attribute. For example, `getattr(X, 'FOOBAR')' is
equivalent to `X.FOOBAR'.
- built-in function: hasattr (OBJECT, NAME)
The arguments are an object and a string. The result is 1 if the
string is the name of one of the object's attributes, 0 if not.
(This is implemented by calling `getattr(object, name)' and seeing
whether it raises an exception or not.)
- built-in function: hash (OBJECT)
Return the hash value of the object (if it has one). Hash values
are 32-bit integers. They are used to quickly compare dictionary
keys during a dictionary lookup. Numeric values that compare equal
have the same hash value (even if they are of different types, e.g.
1 and 1.0).
- built-in function: hex (X)
Convert a number to a hexadecimal string. The result is a valid
Python expression.
- built-in function: id (OBJECT)
Return the `identity' of an object. This is an integer which is
guaranteed to be unique and constant for this object during its
lifetime. (Two objects whose lifetimes are disjunct may have the
same id() value.) (Implementation note: this is the address of the
object.)
- built-in function: input (PROMPT)
Almost equivalent to `eval(raw_input(PROMPT))'. As for
`raw_input()', the prompt argument is optional. The difference is
that a long input expression may be broken over multiple lines
using the backslash convention.
- built-in function: int (X)
Convert a number to a plain integer. The argument may be a plain
or long integer or a floating point number.
- built-in function: len (S)
Return the length (the number of items) of an object. The argument
may be a sequence (string, tuple or list) or a mapping
(dictionary).
- built-in function: long (X)
Convert a number to a long integer. The argument may be a plain or
long integer or a floating point number.
- built-in function: map (FUNCTION, LIST, ...)
Apply FUNCTION to every item of LIST and return a list of the
results. If additional LIST arguments are passed, FUNCTION must
take that many arguments and is applied to the items of all lists
in parallel; if a list is shorter than another it is assumed to be
extended with `None' items. If FUNCTION is `None', the identity
function is assumed; if there are multiple list arguments, `map'
returns a list consisting of tuples containing the corresponding
items from all lists (i.e. a kind of transpose operation). The
LIST arguments may be any kind of sequence; the result is always a
list.
- built-in function: max (S)
Return the largest item of a non-empty sequence (string, tuple or
list).
- built-in function: min (S)
Return the smallest item of a non-empty sequence (string, tuple or
list).
- built-in function: oct (X)
Convert a number to an octal string. The result is a valid Python
expression.
- built-in function: open (FILENAME, MODE)
Return a new file object (described earlier under Built-in Types).
The string arguments are the same as for `stdio''s `fopen()':
FILENAME is the file name to be opened, MODE indicates how the
file is to be opened: `'r'' for reading, `'w'' for writing
(truncating an existing file), and `'a'' opens it for appending.
Modes `'r+'', `'w+'' and `'a+'' open the file for updating,
provided the underlying `stdio' library understands this. On
systems that differentiate between binary and text files, `'b''
appended to the mode opens the file in binary mode. If the file
cannot be opened, `IOError' is raised.
- built-in function: ord (C)
Return the ASCII value of a string of one character. E.g.,
`ord('a')' returns the integer `97'. This is the inverse of
`chr()'.
- built-in function: pow (X, Y)
Return X to the power Y. The arguments must have numeric types.
With mixed operand types, the rules for binary arithmetic
operators apply. The effective operand type is also the type of
the result; if the result is not expressible in this type, the
function raises an exception; e.g., `pow(2, -1)' is not allowed.
- built-in function: range (START, END, STEP)
This is a versatile function to create lists containing arithmetic
progressions. It is most often used in `for' loops. The
arguments must be plain integers. If the STEP argument is
omitted, it defaults to `1'. If the START argument is omitted, it
defaults to `0'. The full form returns a list of plain integers
`[START, START + STEP, START + 2 * STEP, ...]'. If STEP is
positive, the last element is the largest `START + I * STEP' less
than END; if STEP is negative, the last element is the largest
`START + I * STEP' greater than END. STEP must not be zero.
Example:
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
>>>
- built-in function: raw_input (PROMPT)
The string argument is optional; if present, it is written to
standard output without a trailing newline. The function then
reads a line from input, converts it to a string (stripping a
trailing newline), and returns that. When EOF is read, `EOFError'
is raised. Example:
>>> s = raw_input('--> ')
--> Monty Python's Flying Circus
>>> s
'Monty Python\'s Flying Circus'
>>>
- built-in function: reduce (FUNCTION, LIST, INITIALIZER)
Apply the binary FUNCTION to the items of LIST so as to reduce the
list to a single value. E.g., `reduce(lambda x, y: x*y, LIST, 1)'
returns the product of the elements of LIST. The optional
INITIALIZER can be thought of as being prepended to LIST so as to
allow reduction of an empty LIST. The LIST arguments may be any
kind of sequence.
- built-in function: reload (MODULE)
Re-parse and re-initialize an already imported MODULE. The
argument must be a module object, so it must have been successfully
imported before. This is useful if you have edited the module
source file using an external editor and want to try out the new
version without leaving the Python interpreter. Note that if a
module is syntactically correct but its initialization fails, the
first `import' statement for it does not import the name, but does
create a (partially initialized) module object; to reload the
module you must first `import' it again (this will just make the
partially initialized module object available) before you can
`reload()' it.
- built-in function: repr (OBJECT)
Return a string containing a printable representation of an object.
This is the same value yielded by conversions (reverse quotes).
It is sometimes useful to be able to access this operation as an
ordinary function. For many types, this function makes an attempt
to return a string that would yield an object with the same value
when passed to `eval()'.
- built-in function: round (X, N)
Return the floating point value X rounded to N digits after the
decimal point. If N is omitted, it defaults to zero. The result
is a floating point number. Values are rounded to the closest
multiple of 10 to the power minus N; if two multiples are equally
close, rounding is done away from 0 (so e.g. `round(0.5)' is
`1.0' and `round(-0.5)' is `-1.0').
- built-in function: setattr (OBJECT, NAME, VALUE)
This is the counterpart of `getattr'. The arguments are an
object, a string and an arbitrary value. The string must be the
name of one of the object's attributes. The function assigns the
value to the attribute, provided the object allows it. For
example, `setattr(X, 'FOOBAR', 123)' is equivalent to `X.FOOBAR =
123'.
- built-in function: str (OBJECT)
Return a string containing a nicely printable representation of an
object. For strings, this returns the string itself. The
difference with `repr(OBJECT' is that `str(OBJECT' does not always
attempt to return a string that is acceptable to `eval()'; its
goal is to return a printable string.
- built-in function: type (OBJECT)
Return the type of an OBJECT. The return value is a type object.
There is not much you can do with type objects except compare them
to other type objects; e.g., the following checks if a variable is
a string:
>>> if type(x) == type(''): print 'It is a string'
File: python-lib.info, Node: Built-in Modules, Next: Standard Modules, Prev: Built-in Objects, Up: Top
Built-in Modules
****************
The modules described in this chapter are built into the interpreter
and considered part of Python's standard environment: they are always
avaialble.(1)
* Menu:
* sys::
* __builtin__::
* __main__::
* array::
* math::
* time::
* regex::
* marshal::
* struct::
---------- Footnotes ----------
(1) at least in theory -- it is possible to specify at build time that
one or more of these modules should be excluded, but it would be
antisocial to do so.
File: python-lib.info, Node: sys, Next: __builtin__, Prev: Built-in Modules, Up: Built-in Modules
Built-in Module `sys'
=====================
This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the
interpreter. It is always available.
- data of module sys: argv
The list of command line arguments passed to a Python script.
`sys.argv[0]' is the script name. If no script name was passed to
the Python interpreter, `sys.argv' is empty.
- data of module sys: builtin_module_names
A list of strings giving the names of all modules that are compiled
into this Python interpreter. (This information is not available
in any other way -- `sys.modules.keys()' only lists the imported
modules.)
- data of module sys: exc_type
- data of module sys: exc_value
- data of module sys: exc_traceback
These three variables are not always defined; they are set when an
exception handler (an `except' clause of a `try' statement) is
invoked. Their meaning is: `exc_type' gets the exception type of
the exception being handled; `exc_value' gets the exception
parameter (its "associated value" or the second argument to
`raise'); `exc_traceback' gets a traceback object which
encapsulates the call stack at the point where the exception
originally occurred.
- function of module sys: exit (N)
Exit from Python with numeric exit status N. This is implemented
by raising the `SystemExit' exception, so cleanup actions
specified by `finally' clauses of `try' statements are honored,
and it is possible to catch the exit attempt at an outer level.
- data of module sys: exitfunc
This value is not actually defined by the module, but can be set by
the user (or by a program) to specify a clean-up action at program
exit. When set, it should be a parameterless function. This
function will be called when the interpreter exits in any way (but
not when a fatal error occurs: in that case the interpreter's
internal state cannot be trusted).
- data of module sys: last_type
- data of module sys: last_value
- data of module sys: last_traceback
These three variables are not always defined; they are set when an
exception is not handled and the interpreter prints an error
message and a stack traceback. Their intended use is to allow an
interactive user to import a debugger module and engage in
post-mortem debugging without having to re-execute the command
that cause the error (which may be hard to reproduce). The
meaning of the variables is the same as that of `exc_type',
`exc_value' and `exc_tracaback', respectively.
- data of module sys: modules
Gives the list of modules that have already been loaded. This can
be manipulated to force reloading of modules and other tricks.
- data of module sys: path
A list of strings that specifies the search path for modules.
Initialized from the environment variable `PYTHONPATH', or an
installation-dependent default.
- data of module sys: ps1
- data of module sys: ps2
Strings specifying the primary and secondary prompt of the
interpreter. These are only defined if the interpreter is in
interactive mode. Their initial values in this case are `'>>> ''
and `'... ''.
- function of module sys: settrace (TRACEFUNC)
Set the system's trace function, which allows you to implement a
Python source code debugger in Python. The standard modules `pdb'
and `wdb' are such debuggers; the difference is that `wdb' uses
windows and needs STDWIN, while `pdb' has a line-oriented
interface not unlike dbx. See the file `pdb.doc' in the Python
library source directory for more documentation (both about `pdb'
and `sys.trace').
- function of module sys: setprofile (PROFILEFUNC)
Set the system's profile function, which allows you to implement a
Python source code profiler in Python. The system's profile
function is called similarly to the system's trace function (see
`sys.settrace'), but it isn't called for each executed line of
code (only on call and return and when an exception occurs). Also,
its return value is not used, so it can just return `None'.
- data of module sys: stdin
- data of module sys: stdout
- data of module sys: stderr
File objects corresponding to the interpreter's standard input,
output and error streams. `sys.stdin' is used for all interpreter
input except for scripts but including calls to `input()' and
`raw_input()'. `sys.stdout' is used for the output of `print' and
expression statements and for the prompts of `input()' and
`raw_input()'. The interpreter's own prompts and (almost all of)
its error messages go to `sys.stderr'. `sys.stdout' and
`sys.stderr' needn't be built-in file objects: any object is
acceptable as long as it has a `write' method that takes a string
argument.
- data of module sys: tracebacklimit
When this variable is set to an integer value, it determines the
maximum number of levels of traceback information printed when an
unhandled exception occurs. The default is 1000. When set to 0 or
less, all traceback information is suppressed and only the
exception type and value are printed.
File: python-lib.info, Node: __builtin__, Next: __main__, Prev: sys, Up: Built-in Modules
Built-in Module `__builtin__'
=============================
This module provides direct access to all `built-in' identifier of
Python; e.g. `__builtin__.open' is the full name for the built-in
function `open'.
File: python-lib.info, Node: __main__, Next: array, Prev: __builtin__, Up: Built-in Modules
Built-in Module `__main__'
==========================
This module represents the (otherwise anonymous) scope in which the
interpreter's main program executes -- commands read either from
standard input or from a script file.